

var	 TERMINALID      = "";     // 设备号
var	 OPENID          = "";     // 用户openid
var	 DEALERNAME      = "";     // 网点名称
var	 TERMINALNAME    = "";     // 设备名称


var  PREPAYMENTTYPE  = "";     ////收费模式
var STORECHARGE_PACKAGEID="";  //存总订单号

var WXNOUSE=0;

var SEXAREA;  //男女分区
var FLAG;

/*/!* 订单清楚流水号订单号传递类型 *!/
var FINDTYPES_TRADEWATERNO    	= "1";
var FINDTYPES_PACKAGEID       	= "2";*/


/* 断网FLAG */
var OFFLINE = false;
var isStore = false;




/*开箱异常*/
function userOpenExcep(terminalid,boxid,packageid,failtype,endorderState,buttonType){
    var result;
    $.ajax({
        type: 'post',
        dataType: 'json',
        async: false,                       // 同步加载
        url: '/takeControles',
        data:{"terminalid": terminalid,
            "openid":     OPENID,
            "boxid":      boxid,
            "packageid":  packageid,
            "failtype":   failtype, // 失败类型   1:存开箱失败     2:取开箱失败(非补交)  3:取开箱失败(补交)
            "endorder":	  endorderState,   //0:无效不处理  1:结束订单(前提是一存多取的情况)
            "buttontype": buttonType,     // 按钮类型   1:箱门已开(订单结束,同时记录异常) 2:箱门未开(记录异常)
            "types":      "openBoxExcep"},
        contentType: 'application/x-www-form-urlencoded',
        success: function(res){
           // result = res.err_code;
            result = res
        }
    });
    return result;
}





var TELEPHONE = "0571-86468639";
/*拨打管理员电话*/
function takePhonee(){

    console.log(isWeiXin());
    if (isWeiXin()){

       if (TELEPHONE) {
            window.location.href = 'tel:' + TELEPHONE;
        } else {
            $.alert("TELEPHONE为空");
        }
    }else{
        $.alert("抱歉，本功能只对微信浏览器开放。");
    }

}



/** 返回刷新 */
function pushHistory(){
    console.log('all刷新');
    window.addEventListener("popstate", function(e) {
        self.location.reload();
        //  $.toast('666')
    }, false);
    var state = {title : "",url : "#"};

    window.history.replaceState(state, "", "#");

}


/*wx.config({
    jsApiList: ['closeWindow'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
});*/
//签名失败

/** TODO待优化 获取地理位置*/
function myGetLocation(){
        console.log(666);
    if (isWeiXin()) {
        console.log('location1');
            wx.ready(function(){
            console.log('location2');
            wx.getLocation({
                //type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    alert("获取地理位置成功，经纬度为：（" + res.latitude + "，" + res.longitude + "）" );
                    console.log(res);
                    var accuracy = res.accuracy; // 位置精度
                    wx.openLocation({
                        latitude: res.latitude, // 纬度，浮点数，范围为90 ~ -90
                        longitude: res.longitude, // 经度，浮点数，范围为180 ~ -180。
                        name: '杭州东城电子',                // 位置名
                        address: '杭州江干区科业路68号',    // 地址详情说明
                        scale: 20,                      // 地图缩放级别,整形值,范围从1~28。默认为最大
                        infoUrl: ''                    // 在查看位置界面底部显示的超链接,可点击跳转
                    });
                },
                fail: function(error) {
                    $.alert("获取地理位置失败，请确保开启GPS且允许微信获取您的地理位置！");
                },
            });

        });
    } else {
        $.alert("抱歉，本功能只对微信浏览器开放。");
    }
}



/**
 * 格式化收费标准
 * return price;*/
function getCharges(chargeStandard){
    var price = chargeStandard.split(',');
    price.pop();
    for (var i = 0;i < price.length;i++) {
        var reg = /[^:]*:([^:]*)/;
        price[i] = price[i].replace(reg,"$1");
    }
    // console.log(price);
    return price;
}




/** 微信浏览器判断方法 */
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
   // console.log('wxllq');
 //   console.log(ua);//mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko)version/9.0 mobile/13b143 safari/601.1
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}


// //解决横屏和手机键盘挤压问题
// var initViewport = function(height){
//     var metaEl = document.querySelector("#viewportMeta");  //meta标签的id
//     var content = "height=" + height + ",width=device-width,initial-scale=1.0,user-scalable=no";
//     metaEl.setAttribute('name', 'viewport');
//     metaEl.setAttribute('content', content);
// };







// function throttleTake(fn, gapTime) {
//     //sessionStorage.setItem(" _lastTime",0);--放到不会被引用而刷新的页面--payUrl
//     if (gapTime == null || gapTime == undefined) {
//         gapTime = 1200
//     }
//     //var _lastTime = null;
//     var _tlastTime=sessionStorage.getItem("_tlastTime");
//     // 返回新的函数
//     return function () {
//         var _nowTime = + new Date();
//         if (_nowTime - _tlastTime > gapTime || !_tlastTime) {
//             sessionStorage.setItem("_tlastTime",_nowTime);
//
//             fn.apply(this, arguments); //将this和参数传给原函数
//
//         }
//     }
// }


function de(fn, gapTime){
    if (!gapTime) {
        gapTime = 600  //fn执行的间隔时间
    }
    var timer;
    return function(){
        clearTimeout(timer);
        timer=setTimeout(function(){
            fn.apply(this,arguments);
        },gapTime);
    }
}



//数组去重
function  deleRep(arr) {
    for(var i=0;i<arr.length;i++){
        for (var j=i+1; j <arr.length;j++) {
            if(arr[i]==arr[j]){
                arr.splice(j,1);
                j--;
            }
            // if(newarr.indexOf(arr[i])==-1){
            //     newarr.push(arr[i])
            // }
        }
    }
    return arr;
}

function keyword(arr) {
    for (var i = 0; i <arr.length; i++) {
        for (var j = i+1;j<arr.length; j++) {

            if(arr[i].areaname == arr[j].areaname){
                arr.splice(j,1);
                j--;
            }

        }


    }
    return arr;
}



function compare(property) { //箱号排序
    return function (a, b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;//升序,降序为value2 - value1
    }
}



function getUrlParam(name){ //获取地址栏参数方法
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");

    var r = window.location.search.substr(1).match(reg);

    if (r!=null) return unescape(r[2]); return null;
}
// console.log(window.location.search)


//生成二维码方法
function qrCodeNext(url,strHeader,canDom,imgDom){

    var	qrText = url,//要生成二维码的信息,文本或URL
        strFooter = '生成一个二维码',//底部文字描述
        picWidth = 20,//图片额外宽
        picHeight = 60,//图片额外高
        fontSize = 14;//描述文字大小

    var qrcode=canDom.qrcode({
        render: 'canvas',
        text:qrText,
        width:250,
        height:230,
        background: '#ffffff',
        foreground: '#000000'
    });
   // var canvas = $('#qrcode').find('canvas').get(0)
    var canvas = canDom.find('canvas').get(0);
    var img=new Image();
    //console.log(img);
    img.src=canvas.toDataURL('image/png');
    img.onload=function(){
        var w=img.width+20;
        var h=img.height+40;
        canvas.width = w; 
        canvas.height = h;
        var ctx = canvas.getContext('2d');
        //设置画布背景
        ctx.fillStyle='#ffffff';
        ctx.fillRect(0,0, canvas.width, canvas.height);
        //设置文字样式
        ctx.fillStyle = '#000000';
        ctx.font = 'bold 14px Arial';
        ctx.textAlign = 'center';
        //绘制顶部文字描述
        ctx.fillText(strHeader,w/2,60/3);  //文本 x坐标 y坐标
        //绘制二维码
        ctx.drawImage(img,20/2,60/2);  //向画布是绘制图片
        var data=canvas.toDataURL('image/png',1);
        //显示二维码
        var imgCode=new Image();
        imgCode.src=data;
        imgDom.append(imgCode);


    };

}


function explain(){ //说明书
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "/htmlFive/instructions.txt", false);
    xhr.overrideMimeType("text/html;charset=utf-8");//默认为utf-8
    xhr.send(null);
    //console.log(xhr)
    if(xhr.status==200 && xhr.readyState==4 ){
        var text=xhr.responseText;

        $('.text-content').html(text);
        $("#explain").popup();
    }else{
        $.toast('请重试','text');
    }
}



function returnFloat(value){ //格式化金额
    var value=Math.round(parseFloat(value))/100;
    var xsd=value.toString().split(".");
    if(xsd.length==1){
        value=value.toString()+".00";
        return value;
    }
    if(xsd.length>1){
        if(xsd[1].length<2){
            value=value.toString()+"0";
        }
        return value;
    }
}


function ajax(data,url,successFn,isAsync) {
    var async;
    if(isAsync==null){ async=true; }else{async=isAsync;}

    $.ajax({
        type: 'POST',
        async: async,                       // false是同步加载
        dataType: 'json',
        url: url,
        data:data,
        contentType: 'application/x-www-form-urlencoded',
        success: function(res){
            successFn(res);
        },
        error:function () {
            $.hideLoading();
           console.log(data.type+'error')
        }
    });


}









/* 页面底部存取菜单按钮触发动作 //非预约情况下
 *存*/
function btnStore(){
    var terminalid    =  TERMINALID;     // 设备号
    var openid        =  OPENID;         // 用户openid
    var dealername    =  DEALERNAME ;    // 网点名称
    var terminalname  =  TERMINALNAME ;  // 设备名称
    var sex           =  0;
    var timestamp =1000;
    //    window.location.href="/htmlFive/weixin/store/storeOne.jsp?terminalid="+terminalid+"&openid="+openid+"&dealerName="+encodeURI(encodeURI(dealername))+"&terminalName="+terminalname+"&timestamp="+timestamp+"&flag="+2+"&sex="+sex+"";
    window.location.href="/htmlFive/weixin/store/storeOne.jsp?terminalid="+terminalid+"&openid="+openid+"&timestamp="+timestamp+"&flag="+2+"&sex="+sex+"";
    return false;
}

/*取*/
function btnTake(){
    var terminalid    =  TERMINALID;     // 设备号
    var openid        =  OPENID;         // 用户openid
    var dealername    =  DEALERNAME ;    // 网点名称
    var terminalname  =  TERMINALNAME ;  // 设备名称
    var sex           =  0;
    var timestamp     =  1000;
    //    window.location.href="/htmlFive/weixin/takees.jsp?terminalid="+terminalid+"&openid="+openid+"&dealerName="+encodeURI(encodeURI(dealername))+"&terminalName="+terminalname+"&timestamp="+timestamp+"&flag="+2+"&sex="+sex+"";
    window.location.href="/htmlFive/weixin/takees.jsp?terminalid="+terminalid+"&openid="+openid+"&timestamp="+timestamp+"&flag="+2+"&sex="+sex+"";
    return false;
}


//预约情况下
function btnStores(){
    var terminalid    =  TERMINALID;     // 设备号
    var openid        =  OPENID;         // 用户openid
    var dealername    =  DEALERNAME ;    // 网点名称
    var terminalname  =  TERMINALNAME ;  // 设备名称
    var sex           =  SEXAREA;
    var timestamp =1000;
    //window.location.href="/htmlFive/weixin/store/appointment.jsp?terminalid="+terminalid+"&openid="+openid+"&dealerName="+encodeURI(encodeURI(dealername))+"&terminalName="+terminalname+"&timestamp="+timestamp+"&flag="+1+"&sex="+sex+"";
window.location.href="/htmlFive/weixin/store/appointment.jsp?terminalid="+terminalid+"&openid="+openid+"&timestamp="+timestamp+"&flag="+1+"&sex="+sex+"";
    return false;

}



function btnTakes(){
    var terminalid    =  TERMINALID;     // 设备号
    var openid        =  OPENID;         // 用户openid 截取的url
    var dealername    =  DEALERNAME ;    // 网点名称
    var terminalname  =  TERMINALNAME ;  // 设备名称
    var sex           =  SEXAREA;
    var timestamp     =  1000;
    //window.location.href="/htmlFive/weixin/takees.jsp?terminalid="+terminalid+"&openid="+openid+"&dealerName="+encodeURI(encodeURI(dealername))+"&terminalName="+terminalname+"&timestamp="+timestamp+"&flag="+1+"&sex="+sex+"";
    window.location.href="/htmlFive/weixin/takees.jsp?terminalid="+terminalid+"&openid="+openid+"&timestamp="+timestamp+"&flag="+1+"&sex="+sex+"";
    return false;
}